<template>
  <div>
    <!-- 列表数据 -->
    <el-card class="content-card">
      <!-- 工具栏 -->
      <table-toolbar v-model:columns="columns"
                     v-model:size="size"
                     v-model:stripe="stripe"
                     @refresh="handleSearch">
        <!-- 操作区域 -->
        <el-button v-if="multipleSelection.length > 0" v-permission="'admin:recharge:clear'" icon="delete" type="danger" @click="handleBatchDelete">
          {{ multipleSelection.length > 0 ? `清理(${multipleSelection.length})` : '清理' }}
        </el-button>
      </table-toolbar>

      <!-- 列表记录 -->
      <div class="table-wrapper">
        <!-- 列表数据 -->
        <el-table ref="tableRef"
                  v-loading="loading"
                  :data="tableData"
                  :size="size"
                  :stripe="stripe"
                  row-key="id"
                  show-overflow-tooltip
                  @select="handleSelectChange"
                  @select-all="handleSelectAll"
                  @sort-change="handleSortChange">
          <template #empty>
            <el-empty class="table-empty" description="暂无数据"/>
          </template>

          <table-column :columns="columns">
            <template #user_id="scope">
              <UserInfoLink :user-id="scope.row.user_id"/>
            </template>
            <template #capital_type="scope">
              <DictTag v-model="scope.row.capital_type" :circle="false" dict-type="money_capital_type"/>
            </template>

            <template #operations="scope">
              <el-popconfirm v-if="hasPermission('admin:recharge:clear')"
                             :key="scope.row.id"
                             cancel-button-text="放弃"
                             confirm-button-text="确定"
                             icon="WarningFilled"
                             title="您确定要清理此记录?"
                             width="220"
                             @confirm="handleDelete([scope.row.id])">
                <template #reference>
                  <el-button link type="danger">清理</el-button>
                </template>
              </el-popconfirm>
            </template>
          </table-column>
        </el-table>

        <!-- 分页操作 -->
        <el-pagination v-if="totalCount > 0"
                       :current-page="pageQuery.pageNum"
                       :page-size="pageQuery.pageSize"
                       :page-sizes="pageSizes"
                       :total="totalCount"
                       background
                       class="table-pagination"
                       layout="total, sizes, prev, pager, next"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"/>
      </div>
    </el-card>

  </div>
</template>

<script lang="tsx" setup>
import { computed, h, onBeforeMount, ref } from 'vue';
import { QueryForm } from '@/components/query-form';
import useLoading from '@/hooks/use-loading';
import TableColumn, { TableColumnData } from '@/components/table-column/index.vue';
import TableToolbar from '@/components/table-toolbar/index.vue';
import useTableSelection from '@/hooks/use-table-selection';
import { ElLoading, ElMessageBox, ElNotification, TableInstance } from 'element-plus';
import useTable from '@/hooks/use-table.ts';
import { rechargeAdminClear, rechargeAdminList } from '@/api/api-finance.ts';
import { hasPermission } from '@/utils/permission.ts';
import { computedOperateWidth, toDecimal } from '@/utils';
import { UserInfoLink } from '@/components/user-info-link';
import { DictTag } from '@/components/dict-tag';

const props = defineProps({
  userId: {
    type: Number
  },
});
const queryFormRef = ref<InstanceType<typeof QueryForm>>();

// 列表数据
const tableRef = ref<TableInstance>();
const tableData = ref<any[]>([]);
const totalCount = ref(0);

// 操作区域宽度计算
const operateWidth = computed(() => {
  let count = 0
  if (hasPermission('admin:recharge:clear')) count += 1
  return computedOperateWidth(count);
});

// 列设置
const columns = ref<TableColumnData[]>([
  {type: 'selection', width: 45, hidden: operateWidth.value == 0},
  {prop: 'id', label: '编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'user_id', label: '用户编号', width: 110, align: 'center', sortable: 'custom'},
  {prop: 'account', label: '用户账号', minWidth: 120, align: 'right', sortable: 'custom'},
  {prop: 'nickname', label: '用户昵称', minWidth: 140, align: 'right', sortable: 'custom'},
  {prop: 'capital_type', label: '资金类型', minWidth: 120, align: 'center', headerAlign: 'right', sortable: 'custom'},
  {prop: 'amount', label: '操作金额', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'before_amount', label: '操作前资金', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'after_amount', label: '操作后资金', minWidth: 130, align: 'right', sortable: 'custom', render: (scope, val) => <span>{toDecimal(val, 4)}</span>},
  {prop: 'create_time', label: '操作时间', minWidth: 180, align: 'right', sortable: 'custom'},
  {prop: 'operate_account', label: '操作者', minWidth: 120, align: 'right', sortable: 'custom'},
  {prop: 'reason', label: '操作原因', minWidth: 180, align: 'right', sortable: 'custom'},
]);

onBeforeMount(() => {
  if (operateWidth.value > 0) {
    columns.value.push({prop: 'operations', label: '操作', fixed: 'right', width: operateWidth.value, align: 'center', headerAlign: 'center'},)
  }
  // 重置查询表单
  handleResetQueryForm();
});

const [loading, setLoading] = useLoading(false);
const {tableMethods, tableState} = useTable(() => fetchDataList(), queryFormRef, true, true);
const {size, stripe, showQueryForm, pageQuery, pageSizes} = tableState;
const {handleSizeChange, handleCurrentChange, handleSortChange, handleResetForm} = tableMethods;
const {handleSelectChange, handleSelectAll, multipleSelection, clearSelection} = useTableSelection(tableData, tableRef);

// 数据查询
const fetchDataList = async () => {
  setLoading(true);
  try {
    // 查询数据
    const {data} = await rechargeAdminList({
      page_num: pageQuery.pageNum,
      page_size: pageQuery.pageSize,
      order_mode: pageQuery.orderMode,
      order_column: pageQuery.orderColumn,
      user_id: props.userId,
    });
    // 结果转换
    tableData.value = data.list;
    totalCount.value = data.pages.total_count;
  } catch (err) {
  } finally {
    setLoading(false);
  }
};

// 刷新数据
const handleSearch = () => {
  fetchDataList();
};

// 重置查询条件
const handleResetQueryForm = () => {
  clearSelection();
  handleResetForm();
};

// 对外提供部分方法
defineExpose({handleSearch});

/** 批量删除操作 */
const handleBatchDelete = () => {
  if (!multipleSelection.value.length) {
    return;
  }
  // 需要清理的编号
  const itemIds = multipleSelection.value.map((item) => {
    return item.id;
  });

  ElMessageBox({
    title: '操作确认',
    message: h('p', null, [
      '您确定要清理选中的 ',
      h('span', {style: 'font-weight: bold'}, itemIds.length + '条'),
      ' 记录吗？',
    ]),
    type: 'warning',
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '放弃',
  }).then((action) => {
    // 调用函数清理清理
    handleDelete(itemIds);
  }).catch(() => {

  });
}

/** 删除操作 */
const handleDelete = (ids: number[]) => {
  const loading = ElLoading.service({
    lock: true,
    text: '正在处理中...',
    background: 'rgba(0, 0, 0, 0.2)'
  })
  rechargeAdminClear(ids).then(() => {
    // 提示信息
    ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
    // 清理选中信息
    clearSelection(ids);
    // 刷新列表数据
    handleSearch();
  }).finally(() => loading.close())
};

</script>

<style lang="scss" scoped>

</style>
